package com.example.niuke.controller;

import com.example.niuke.entity.Comment;
import com.example.niuke.entity.DiscussPost;
import com.example.niuke.entity.Event;
import com.example.niuke.event.EventProducer;
import com.example.niuke.service.CommentService;
import com.example.niuke.service.DiscussPostService;
import com.example.niuke.util.CommunityConstant;
import com.example.niuke.util.HostHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {
    /**
     * Auther sun
     * 给帖子或回复评论
     * DATE 2022/4/17 10:13
     * VERSION 1.0
     */

    @Resource
    private CommentService commentService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private EventProducer eventProducer;
    @Resource
    private DiscussPostService discussPostService;

    @PostMapping("/add/{discussPostId}")
    public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {

        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.addComment(comment);


        HashMap<String, Object> data = new HashMap<>();
        data.put("postId", discussPostId);
        //触发评论事件
        Event event = new Event().builder()
                .topic(TOPIC_COMMENT)
                .userId(hostHolder.getUser().getId())
                .entityType(comment.getEntityType())
                .entityId(comment.getEntityId())
                .data(data)
                .build();
                        //setData("postId",discussPostId);

        if(comment.getEntityType() == ENTITY_TYPE_POST) {
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        } else if(comment.getEntityType() == ENTITY_TYPE_COMMENT) {
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        eventProducer.fireEvent(event);

        /*if(comment.getEntityType()==ENTITY_TYPE_POST) {
            event = new Event()
                    .builder()
                    .topic(TOPIC_PUBLISH)
                    .userId(hostHolder.getUser().getId())
                    .entityType(ENTITY_TYPE_POST)
                    .entityId(discussPostId)
                    .build();
            eventProducer.fireEvent(event);
        }*/

        return "redirect:/discuss/detail/" + discussPostId;
    }


}
